package com.enqualcomm.kids.mvp.login.wx;

import android.app.Activity;

import com.enqualcomm.kids.config.userdefault.AppDefault;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.Map;

import common.utils.MyLogger;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Func1;

/**
 * Created by yinzhiqun on 2016/5/17.
 * 第三方登录
 * 对应的Activity要重写onActivityResult()并调用UMShareAPI.get(activity).onActivityResult();
 */
public class OauthService {
    //删除授权使用的接口是mShareAPI.deleteOauth(AuthActivity.this, platform, umdelAuthListener);
    //获取应用安装信息mShareAPI.isInstall(this, SHARE_MEDIA.WEIXIN)

    /**
     * 微信登录
     */
    public Observable<Boolean> doOauthVerifyWX(Activity activity) {
        SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
        return Observable.create(new OauthObservable(platform, activity))
                .flatMap(new Function(new UserInfoObservable(platform, activity)));
    }
//    /**
//     * 微信登录
//     */
//    public Observable<String> doOauthVerifyWX(Activity activity) {
//        SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
//        return Observable.create(new OauthObservable(platform, activity));
////                .flatMap(new Function(new UserInfoObservable(platform,activity)));
//    }

    /**
     * QQ登录
     */
    public Observable<Boolean> doOauthVerifyQQ(Activity activity) {
        SHARE_MEDIA platform = SHARE_MEDIA.QQ;
        return Observable.create(new OauthObservable(platform, activity))
                .flatMap(new Function(new UserInfoObservable(platform, activity)));
    }

    /**
     * 新浪微博登录
     */
    public Observable<Boolean> doOauthVerifySina(Activity activity) {
        SHARE_MEDIA platform = SHARE_MEDIA.SINA;
        return Observable.create(new OauthObservable(platform, activity))
                .flatMap(new Function(new UserInfoObservable(platform, activity)));
    }

    /**
     * Facebook登录
     */
    public Observable<Boolean> doOauthVerifyFacebook(Activity activity) {
        SHARE_MEDIA platform = SHARE_MEDIA.FACEBOOK;
        return Observable.create(new OauthObservable(platform, activity))
                .flatMap(new Function(new UserInfoObservable(platform, activity)));
    }

    /**
     * Twitter登录
     */
    public Observable<Boolean> doOauthVerifyTwitter(Activity activity) {
        SHARE_MEDIA platform = SHARE_MEDIA.TWITTER;
        return Observable.create(new OauthObservable(platform, activity))
                .flatMap(new Function(new UserInfoObservable(platform, activity)));
    }

    private static class OauthObservable implements Observable.OnSubscribe<String> {
        SHARE_MEDIA platform;
        Activity activity;

        public OauthObservable(SHARE_MEDIA platform, Activity activity) {
            this.platform = platform;
            this.activity = activity;
        }

        @Override
        public void call(final Subscriber<? super String> subscriber) {
            UMShareAPI.get(activity).doOauthVerify(activity, platform, new UMAuthListener() {
                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                    if (map == null) {
//                        MyLogger.jLog().i(platform.name() + ": map==null");
                        return;
                    }
                    MyLogger.jLog().i("onComplete" + i);
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        MyLogger.jLog().i(entry.getKey() + " : " + entry.getValue());
                    }
                    String userid = map.get("uid");
                    if (userid == null) {
                        userid = map.get("openid");
                    }
                    if (userid == null) {
                        userid = map.get("usid");
                    }
                    userid = userid + "_" + platform.name();//避免不同平台userid重复

//                    String expires_in = map.get("expires_in");
//                    long expires;
//                    if (expires_in == null) {
//                        expires = Long.MAX_VALUE;
//                    } else {
//                        long l = Long.parseLong(expires_in);
//                        expires = System.currentTimeMillis() + (l<10000?l*60000:l);
//                    }

//                    AppDefault appDefault = new AppDefault();
//                    appDefault.setUserid(userid);
//                    appDefault.setExpires(expires);

                    subscriber.onNext(userid);
                    subscriber.onCompleted();
                }

                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                    throwable.printStackTrace();
                    subscriber.onNext(null);
                    subscriber.onCompleted();
                }

                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {
                    subscriber.onNext(null);
                    subscriber.onCompleted();
                }
            });
        }
    }


    public static boolean checkAccessToken(AppDefault appDefault) {
        return appDefault.getUserid() != null;
//        if (appDefault.getUserid() != null) {
//            long expires = appDefault.getExpires();
//            if (expires - System.currentTimeMillis() > 0) {
//                return true;
//            }
//        }
//        return false;
    }

    private static class Function implements Func1<String, Observable<Boolean>> {
        UserInfoObservable observable;

        public Function(UserInfoObservable observable) {
            this.observable = observable;
        }

        @Override
        public Observable<Boolean> call(String userid) {
            if (userid == null) {
                //登录失败
                return Observable.just(false);
            } else {
                observable.setUserid(userid);
                return Observable.create(observable);
            }
        }
    }

    private static class UserInfoObservable implements Observable.OnSubscribe<Boolean> {
        SHARE_MEDIA platform;
        Activity activity;
        String userid;

        public UserInfoObservable(SHARE_MEDIA platform, Activity activity) {
            this.platform = platform;
            this.activity = activity;
        }

        public void setUserid(String userid) {
            this.userid = userid;
        }

        @Override
        public void call(final Subscriber<? super Boolean> subscriber) {
            UMShareAPI.get(activity).getPlatformInfo(activity, platform, new UMAuthListener() {
                @Override
                public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                    if (map == null) {
//                        MyLogger.jLog().i(platform.name() + ": map==null");
                        return;
                    }

                    MyLogger.jLog().i("onComplete" + i);
                    for (Map.Entry<String, String> entry : map.entrySet()) {
                        MyLogger.jLog().i(entry.getKey() + " : " + entry.getValue());
                    }

                    String image_url = null;
                    String name = null;
                    String unionid = null;
                    boolean gender = true;
                    switch (share_media.name()) {
                        case "QQ":
                            image_url = map.get("profile_image_url");
                            name = map.get("screen_name");
                            gender = "男".equals(map.get("gender"));
                            break;
                        case "WEIXIN":
                            image_url = map.get("headimgurl");
                            name = map.get("nickname");
                            gender = "1".equals(map.get("sex"));
                            unionid = map.get("unionid");
                            break;
                        case "SINA":
                            String result = map.get("result");
                            try {
                                JSONObject obj = (JSONObject) new JSONTokener(result).nextValue();
                                image_url = obj.optString("profile_image_url");
                                name = obj.optString("screen_name");
                                gender = "m".equals(obj.optString("gender"));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                            break;
                        case "FACEBOOK":
                            image_url = map.get("profilePictureUri");
                            name = map.get("name");
                            break;
                    }

//                    UserDefault userDefault = new UserDefault(userid);
//                    if (name!=null){
//                        userDefault.setName(name);
//                    }
//                    if (image_url!=null) {
//                        userDefault.setHeaderImage(image_url);
//                    }
//                    userDefault.setGender(gender);
                    AppDefault appDefault = new AppDefault();
                    appDefault.setWXUserid(unionid);
                    appDefault.setWXUserNickName(name);
                    appDefault.setWXUserHeadUrl(image_url);

                    subscriber.onNext(true);
                    subscriber.onCompleted();
                }

                @Override
                public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                    subscriber.onNext(false);
                    subscriber.onCompleted();
                }

                @Override
                public void onCancel(SHARE_MEDIA share_media, int i) {
                    subscriber.onNext(false);
                    subscriber.onCompleted();
                }
            });
        }
    }
}
